package com.shangze.test.net;

import com.shangze.test.api.UriUtils;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by yjm on 2017/10/25.
 * 网络实现类
 */

public class NetHttpApi {
    private Retrofit mRetrofit;
    // TODO: 2017/10/25 设置请求超时时间
    private static final int REQUEST_TIME = 10;
    private static NetHttpApi instance;
    private NetHttpApi() {
        OkHttpClient.Builder client = new OkHttpClient.Builder();
        client.connectTimeout(REQUEST_TIME, TimeUnit.SECONDS)
                .readTimeout(REQUEST_TIME, TimeUnit.SECONDS)
                .writeTimeout(REQUEST_TIME, TimeUnit.SECONDS);
        // Log信息拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //设置 Debug Log 模式
        client.addInterceptor(loggingInterceptor);
//            }
        OkHttpClient okHttpClient = client.build();
        mRetrofit = new Retrofit.Builder()
                .client(client.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(UriUtils.API_SERVER_URL)
                .client(okHttpClient)
                .build();


    }

    public static NetHttpApi getInstance() {
        if (instance == null) {
            synchronized (NetHttpApi.class) {
                if (instance == null) {
                    instance = new NetHttpApi();
                }
            }
        }
        return instance;
    }

    public <T> T getService(Class<T> service) {
        return mRetrofit.create(service);
    }
}
